package com.srwl.mytx.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.LinearInterpolator;

import com.srwl.mytx.R;

public class MyTextView extends androidx.appcompat.widget.AppCompatTextView {
    private static final String TAG = "MyTextView";
    private float position = 1;
    private int startColor;
    private int endColor;
    private boolean horizontalScroll;
    private LinearGradient mLinearGradient;
    private boolean isFirst = true;
    private boolean isFirstAnimate = true;
    private Rect mTextBound;
    private TextPaint mPaint;
    private String mTipText;
    private int offSetX;
    private ValueAnimator animator;

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);//获取配置属性
        position = tArray.getFloat(R.styleable.MyTextView_colorPosition, 1f);
        startColor = tArray.getInt(R.styleable.MyTextView_startColor, getResources().getColor(R.color.white));
        endColor = tArray.getInt(R.styleable.MyTextView_endColor, getResources().getColor(R.color.text_gray));
        horizontalScroll = tArray.getBoolean(R.styleable.MyTextView_horizontal_scroll, true);
        tArray.recycle();
        mTextBound = new Rect();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        mTipText = getText().toString();
        mPaint = getPaint();
        mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);
        if (horizontalScroll && mTextBound.width() > getMeasuredWidth() && animator == null) {

            Log.d(TAG, "onDraw: 字体需要滚动  mTextBound.width() :" + mTextBound.width());
            animator = ValueAnimator.ofInt(-getMeasuredWidth(), mTextBound.width());
            animator.setRepeatMode(ValueAnimator.RESTART);
            animator.setRepeatCount(ValueAnimator.INFINITE);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    if (isFirstAnimate) {
                        offSetX = (int) animation.getAnimatedValue();
                        //   Log.d(TAG, "onAnimationUpdate:offSetX: " + offSetX);
                        if (offSetX >= mTextBound.width() - getMeasuredWidth()) {
                            isFirstAnimate = false;
                            animator.setCurrentPlayTime(mTipText.length() * 1000 - 5);
                        }
                        offSetX += getMeasuredWidth();//第一个循环周期内，上个一个MeasuredWidth，为了让第一次滚动的时候，文字是从最左边开始滚动的

                    } else {
                        offSetX = (int) animation.getAnimatedValue();
                        // Log.d(TAG, "onAnimationUpdate: 第一次滚动之后   offSetX:  "+offSetX);
                    }


                    invalidate();
                }
            });
            animator.setDuration(mTipText.length() * 1000);//字体长度的值等于一个滚动周期的时间秒
            animator.setInterpolator(new LinearInterpolator());
            animator.setStartDelay(1000);
            animator.start();
        } else if (mTextBound.width() <= getMeasuredWidth() && animator != null && animator.isRunning()) {
            animator.cancel();
            animator=null;
        }


        generateLinearGradient();
        mPaint.setShader(mLinearGradient);
        int startX = (getMeasuredWidth() / 2 - mTextBound.width() / 2) < 0 ? 0 : (getMeasuredWidth() / 2 - mTextBound.width() / 2);

        canvas.drawText(mTipText, startX - offSetX, getBaseline(), mPaint);
    }

    /**
     * 每次重新生成LinearGradient感觉不科学，以后是否能重新LinearGradient，直接设置positions
     */
    private void generateLinearGradient() {
        mLinearGradient = new LinearGradient(0, 0, 0, getMeasuredHeight(), new int[]{startColor, startColor, endColor, endColor}, new float[]{0f, position, position, 1}, Shader.TileMode.CLAMP);
    }

    public void setColorPosition(float position) {
        if (this.position == position) {
            return;
        }
        this.position = position;
        requestLayout();
    }

    public void showStartColor() {
        if (position == 1) {
            return;
        }
        position = 1;
        requestLayout();
    }

    public void showEndColor() {
        if (position == 0) {
            return;
        }
        position = 0;
        requestLayout();
    }

    public void setEndTextColor(int endColor) {
        this.endColor = endColor;
    }

    public void setStartTextColor(int startColor) {
        this.startColor = startColor;
    }



    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.d(TAG, "onDetachedFromWindow: 执行了");
        if (animator != null && animator.isRunning()) {
            animator.cancel();
            animator = null;
        }
    }
}
